package net.wangliping.android.tools.util;

import java.io.DataOutputStream;
import java.io.InputStream;

import android.util.Log;

public class ShellCommand {
	
	public static boolean isMachineRoot() {
		int ret = -1;
		if ((ret = execCmd("su", null)) != 0) {
			Log.d("ROOT", "ret = " + ret);
			return true;
		}
		
		Log.d("ROOT", "ret = " + ret);
		return false;
	}

	public static int execCmd(String command, StringBuffer cmdResult) {
		int ret = -1;

		InputStream is = null;
		Process process = null;

		try {
			process = Runtime.getRuntime().exec(command);
			is = process.getInputStream();
			ret = process.waitFor();
		} catch (Exception e) {
			return ret;
		} finally {
			try {
				if (cmdResult != null)
					cmdResult.append(Convert.stream2string(is));
				is.close();
				process.destroy();
			} catch (Exception e) {
			}
		}
		return ret;
	}

	public static int execRootCmd(String command, StringBuffer cmdResult) {
		int ret = -1;

		InputStream is = null;
		Process process = null;
		DataOutputStream os = null;
		try {
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			is = process.getInputStream();
			os.write((command + "\n").getBytes("UTF-8"));
			os.writeBytes("exit\n");
			os.flush();
			ret = process.waitFor();
		} catch (Exception e) {
			return ret;
		} finally {
			try {
				if (os != null) {
					if (cmdResult != null)
						cmdResult.append(Convert.stream2string(is));
					is.close();
					os.close();
				}
				process.destroy();
			} catch (Exception e) {
			}
		}
		return ret;
	}

}
